import { message, Modal } from 'antd';
import React, { PropsWithChildren } from 'react';
import { ProColumns, ProTable } from '@ant-design/pro-table';
import { UserType } from '@/models/user';
import { TeamType } from '@/models/team';
import { applyJoinTeam } from '@/services/applyService';
import { ApplyType } from '@/models/apply';

interface UpdateModalProps {
  oldData: TeamType.TeamVo;
  modalVisible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
  loginUser: ProColumns<UserType.UserVO>;
}

/***
 *  申请加入队伍
 * @param fields
 */
const updateBase = async (fields: ApplyType.ApplyJoinTeamRequest) => {
  if (fields.userId <= 0) {
    message.loading('请先进行登入');
    return false;
  }
  const hide = message.loading('正在申请');
  try {
    await applyJoinTeam({
      ...fields,
    });
    hide();
    message.success('申请成功');
    return true;
  } catch (error) {
    hide();
    message.error('申请失败，不要反复申请');
    return false;
  }
};

/***
 *  更新数据模型框
 * @param props
 */
const ApplyJoinTeam: React.FC<PropsWithChildren<UpdateModalProps>> = (
  props,
) => {
  const { oldData, modalVisible, onSubmit, onCancel, loginUser } = props;

  /***
   * 表格列配置
   */
  const columns: ProColumns<TeamType.Team>[] = [
    {
      title: '申请描述',
      dataIndex: 'teamDescription',
      valueType: 'textarea',
    },
  ];

  return (
    <Modal
      destroyOnClose
      title="申请"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<TeamType.Team, TeamType.Team>
        rowKey="id"
        type="form"
        columns={columns}
        onSubmit={async (value) => {
          const success = await updateBase({
            // @ts-ignore
            applyContent: value.teamDescription,
            // @ts-ignore
            teamId: oldData.id,
            // @ts-ignore
            userId: loginUser?.id || 0,
          });
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};

export default ApplyJoinTeam;
